package com.itheima.search.listen;

import com.alibaba.fastjson.JSON;
import com.itheima.search.domain.ItemDoc;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class ListenRabbitmq {

    @Autowired
    RestHighLevelClient client;
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name="item.update.queue"),
            exchange = @Exchange(name = "item.direct"),
            key = "item.update"
    ))
    public void handUpdateMessage(String msg) throws IOException {
        ItemDoc itemDoc = JSON.parseObject(msg, ItemDoc.class);
        IndexRequest request=new IndexRequest("item");
        request.id(itemDoc.getId().toString());
        request.source(JSON.toJSONString(itemDoc), XContentType.JSON);
        client.index(request, RequestOptions.DEFAULT);
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name="item.delete.queue"),
            exchange = @Exchange(name = "item.direct"),
            key = "item.delete"
    ))
    public void handDeleteMessage(String id) throws IOException {
        DeleteRequest request=new DeleteRequest("item",id);
        client.delete(request, RequestOptions.DEFAULT);
    }



}
